{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Title: #Simplify Path"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Difficulty: #Medium"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Category Title: #Algorithms"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Tag Slug: #stack #string"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Name Translated: #栈 #字符串"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Solution Name: simplifyPath"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Translated Title: #简化路径"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Translated Content:\n",
    "<p>给你一个字符串 <code>path</code> ，表示指向某一文件或目录的 Unix 风格 <strong>绝对路径 </strong>（以 <code>'/'</code> 开头），请你将其转化为更加简洁的规范路径。</p>\n",
    "\n",
    "<p class=\"MachineTrans-lang-zh-CN\">在 Unix 风格的文件系统中，一个点（<code>.</code>）表示当前目录本身；此外，两个点 （<code>..</code>） 表示将目录切换到上一级（指向父目录）；两者都可以是复杂相对路径的组成部分。任意多个连续的斜杠（即，<code>'//'</code>）都被视为单个斜杠 <code>'/'</code> 。 对于此问题，任何其他格式的点（例如，<code>'...'</code>）均被视为文件/目录名称。</p>\n",
    "\n",
    "<p>请注意，返回的 <strong>规范路径</strong> 必须遵循下述格式：</p>\n",
    "\n",
    "<ul>\n",
    "\t<li>始终以斜杠 <code>'/'</code> 开头。</li>\n",
    "\t<li>两个目录名之间必须只有一个斜杠 <code>'/'</code> 。</li>\n",
    "\t<li>最后一个目录名（如果存在）<strong>不能 </strong>以 <code>'/'</code> 结尾。</li>\n",
    "\t<li>此外，路径仅包含从根目录到目标文件或目录的路径上的目录（即，不含 <code>'.'</code> 或 <code>'..'</code>）。</li>\n",
    "</ul>\n",
    "\n",
    "<p>返回简化后得到的 <strong>规范路径</strong> 。</p>\n",
    "\n",
    "<p> </p>\n",
    "\n",
    "<p><strong>示例 1：</strong></p>\n",
    "\n",
    "<pre>\n",
    "<strong>输入：</strong>path = \"/home/\"\n",
    "<strong>输出：</strong>\"/home\"\n",
    "<strong>解释：</strong>注意，最后一个目录名后面没有斜杠。 </pre>\n",
    "\n",
    "<p><strong>示例 2：</strong></p>\n",
    "\n",
    "<pre>\n",
    "<strong>输入：</strong>path = \"/../\"\n",
    "<strong>输出：</strong>\"/\"\n",
    "<strong>解释：</strong>从根目录向上一级是不可行的，因为根目录是你可以到达的最高级。\n",
    "</pre>\n",
    "\n",
    "<p><strong>示例 3：</strong></p>\n",
    "\n",
    "<pre>\n",
    "<strong>输入：</strong>path = \"/home//foo/\"\n",
    "<strong>输出：</strong>\"/home/foo\"\n",
    "<strong>解释：</strong>在规范路径中，多个连续斜杠需要用一个斜杠替换。\n",
    "</pre>\n",
    "\n",
    "<p><strong>示例 4：</strong></p>\n",
    "\n",
    "<pre>\n",
    "<strong>输入：</strong>path = \"/a/./b/../../c/\"\n",
    "<strong>输出：</strong>\"/c\"\n",
    "</pre>\n",
    "\n",
    "<p> </p>\n",
    "\n",
    "<p><strong>提示：</strong></p>\n",
    "\n",
    "<ul>\n",
    "\t<li><code>1 <= path.length <= 3000</code></li>\n",
    "\t<li><code>path</code> 由英文字母，数字，<code>'.'</code>，<code>'/'</code> 或 <code>'_'</code> 组成。</li>\n",
    "\t<li><code>path</code> 是一个有效的 Unix 风格绝对路径。</li>\n",
    "</ul>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Description: [simplify-path](https://leetcode.cn/problems/simplify-path/description/)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Solutions: [simplify-path](https://leetcode.cn/problems/simplify-path/solutions/)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test_cases = ['\"/home/\"', '\"/../\"', '\"/home//foo/\"']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def getNextToken(self, path, startingIndex):\n",
    "        if startingIndex >= len(path):\n",
    "            return ('', startingIndex)\n",
    "        \n",
    "        # skip leading /\n",
    "        currIndex = 0\n",
    "        for i in range(startingIndex, len(path)):\n",
    "            if path[i] != '/':\n",
    "                currIndex = i\n",
    "                break\n",
    "        \n",
    "        if currIndex >= len(path):\n",
    "            return ('', currIndex)\n",
    "        \n",
    "        token = []\n",
    "        endingIndex = len(path)\n",
    "        for i in range(currIndex, len(path)):\n",
    "            if path[i] == '/':\n",
    "                endingIndex = i\n",
    "                break\n",
    "            else:\n",
    "                token.append(path[i])\n",
    "        \n",
    "        return (''.join(token), endingIndex) \n",
    "                \n",
    "    def simplifyPath(self, path: str) -> str:\n",
    "        \n",
    "        res = ['/']\n",
    "        startingIndex = 0\n",
    "        while True:\n",
    "            (token, startingIndex) = self.getNextToken(path, startingIndex)\n",
    "            if token == '':\n",
    "                break\n",
    "            \n",
    "            if token == '.':\n",
    "                continue\n",
    "            elif token == '..':\n",
    "                if len(res) > 1:\n",
    "                    res.pop()\n",
    "            else:\n",
    "                res.append(token + '/')\n",
    "        \n",
    "        if len(res) > 1:\n",
    "            res[-1] = res[-1][:-1]\n",
    "        return ''.join(res)\n",
    "                "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def simplifyPath(self, path):\n",
    "        \"\"\"\n",
    "        :type path: str\n",
    "        :rtype: str\n",
    "        \"\"\"\n",
    "        return self.way1(path)\n",
    "    def way1(self,path):#niubility\n",
    "        s = path.split('/')\n",
    "        stack = []\n",
    "        stack.append('/')\n",
    "        ans = ''\n",
    "        for i in range(len(s)):\n",
    "            if not s[i] or s[i] == '.':\n",
    "                continue\n",
    "            if s[i] == '..':\n",
    "                if len(stack) - 2 <= 0:\n",
    "                    continue\n",
    "                else:\n",
    "                    stack.pop()\n",
    "                    stack.pop()\n",
    "            else:\n",
    "                stack.append(s[i])\n",
    "                stack.append('/')\n",
    "        for i in stack[:-1]:\n",
    "            ans += i\n",
    "        if not ans:\n",
    "            ans = '/'\n",
    "        return ans\n",
    "                \n",
    "            "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def simplifyPath(self, path: 'str') -> 'str':\n",
    "        i = 1\n",
    "        while i < len(path):\n",
    "            while i < len(path) and path[i] == '/' and path[i - 1] == '/':\n",
    "                path = path[:i] + path[i + 1:]\n",
    "            i += 1\n",
    "        i -= 1\n",
    "        if path[-1] == '/':\n",
    "            path = path[:-1]\n",
    "        path = path[1:]\n",
    "        ele = path.split('/')\n",
    "        stack = []\n",
    "        for i in ele:\n",
    "            if i == \"..\":\n",
    "                if stack != []:\n",
    "                    stack.pop()\n",
    "            elif i == \".\":\n",
    "                continue\n",
    "            else:\n",
    "                stack.append(i)\n",
    "        if stack == []:\n",
    "            return \"/\"\n",
    "        res = \"/\"\n",
    "        for i in stack:\n",
    "            res = res + i + \"/\"\n",
    "        return res[:-1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class TreeNode:\n",
    "    def __init__(self, x):\n",
    "        self.val = x\n",
    "        self.children = []\n",
    "        self.parent = None\n",
    "\n",
    "\n",
    "class Solution:\n",
    "    def simplifyPath(self, path):\n",
    "        \"\"\"\n",
    "        :type path: str\n",
    "        :rtype: str\n",
    "        \"\"\"\n",
    "        root = TreeNode('/')\n",
    "        p = root\n",
    "        lst = ['.', '..']\n",
    "        for item in path.split('/'):\n",
    "            if item:\n",
    "                if item not in lst:\n",
    "                    tmp = TreeNode(item)\n",
    "                    tmp.parent = p\n",
    "                    p.children.append(tmp)\n",
    "                    p = tmp\n",
    "                elif item == '.':\n",
    "                    continue\n",
    "                else:\n",
    "                    if p.parent:\n",
    "                        p = p.parent\n",
    "                    else:\n",
    "                        p = root\n",
    "\n",
    "        res = ''\n",
    "        while p:\n",
    "            res = p.val + '/' + res\n",
    "            p = p.parent\n",
    "        res= res[1:]\n",
    "        if res != '/':\n",
    "            res = res[:-1]\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def simplifyPath(self, path):\n",
    "        \"\"\"\n",
    "        :type path: str\n",
    "        :rtype: str\n",
    "        \"\"\"\n",
    "        stack = []\n",
    "        i,j = 0,1\n",
    "        while j<len(path)-1:\n",
    "            if path[j] == '/':\n",
    "                if len(path[i:j+1]) == 2:\n",
    "                    pass\n",
    "                elif path[i+1:j] == '.':\n",
    "                    pass\n",
    "                elif path[i+1:j] == '..':\n",
    "                    if stack:\n",
    "                        stack.pop()\n",
    "                else:\n",
    "                    stack.append(path[i+1:j])\n",
    "                    #print(stack)\n",
    "                i = j\n",
    "            j = j+1\n",
    "        if path[-1] == '/':\n",
    "            path = path[:-1]\n",
    "        if path[i:] == '/..':\n",
    "            if stack:\n",
    "                stack.pop()\n",
    "        elif path[i:] != '/.' and len(path[i:])>1:\n",
    "            stack.append(path[i+1:])\n",
    "        ans = '/'\n",
    "        for s in stack:\n",
    "            ans += s+'/'\n",
    "        return ans[:-1] if len(ans)>1 else ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def simplifyPath(self, path):\n",
    "        \"\"\"\n",
    "        :type path: str\n",
    "        :rtype: str\n",
    "        \"\"\"\n",
    "        stack = list()\n",
    "        path = [p for p in path.split('/') if p]\n",
    "        for f in path:\n",
    "            if f == '.': \n",
    "                continue\n",
    "            elif f == '..': \n",
    "                if stack: \n",
    "                    stack.pop()\n",
    "            else: \n",
    "                stack.append(f)\n",
    "\n",
    "        return '/'+'/'.join(stack)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def simplifyPath(self, path):\n",
    "        \"\"\"\n",
    "        :type path: str\n",
    "        :rtype: str\n",
    "        \"\"\"\n",
    "        \n",
    "        stack = []\n",
    "        dirs = path.split('/')\n",
    "        \n",
    "        for dir in dirs:\n",
    "            if not dir or dir == '.':\n",
    "                continue\n",
    "            elif dir == '..':\n",
    "                if stack:\n",
    "                    stack.pop()    \n",
    "            else:\n",
    "                stack.append(dir)\n",
    "        \n",
    "        return '/' + '/'.join(stack)\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def simplifyPath(self, path):\n",
    "        \"\"\"\n",
    "        :type path: str\n",
    "        :rtype: str\n",
    "        \"\"\"\n",
    "        path = path.split(\"/\")\n",
    "        res = []\n",
    "        for x in path:\n",
    "            if x ==\"..\":\n",
    "                if len(res)>=2:\n",
    "                    res = res[:-2]\n",
    "            elif x!=\".\" and x!=\"\":\n",
    "                res.append(\"/\")\n",
    "                res.append(x)\n",
    "        if not res:\n",
    "            return \"/\"\n",
    "        return \"\".join(res)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def simplifyPath(self, path):\n",
    "        ans = []\n",
    "        path = path.split('/')\n",
    "        path = [i for i in path if i != '' and i != '.']\n",
    "        for i in path:\n",
    "            if i != '..':\n",
    "                ans.append(i)\n",
    "            elif ans:\n",
    "                ans.pop()\n",
    "        return '/' + '/'.join(ans)\n",
    "    #python nb"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def simplifyPath(self, path):\n",
    "        \"\"\"\n",
    "        :type path: str\n",
    "        :rtype: str\n",
    "        \"\"\"\n",
    "        if not path:\n",
    "            return path\n",
    "        s = path.split(\"/\")\n",
    "        r = []\n",
    "        for i in range(0, len(s)):\n",
    "            if s[i] == '' or s[i] == '.':\n",
    "                continue\n",
    "            elif s[i] == '..':\n",
    "                if r:\n",
    "                    r.pop()\n",
    "            else:\n",
    "                r.append(s[i])\n",
    "        print(r)\n",
    "        return \"/\"+\"/\".join(r)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def simplifyPath(self, path):\n",
    "        \"\"\"\n",
    "        :type path: str\n",
    "        :rtype: str\n",
    "        \"\"\"\n",
    "        res = [] # 有效路径记录在数组里，便于前溯\n",
    "        temp = ''\n",
    "        for i in range(len(path)):\n",
    "            if (path[i] == \"/\" and temp != \"\") or (i == len(path)-1):\n",
    "                if i == len(path)-1 and path[i] != \"/\":\n",
    "                    temp = temp + path[i] \n",
    "                if temp == \"..\":\n",
    "                    res = res[:-1]\n",
    "                elif temp != \".\" and temp != \"\":\n",
    "                    res.append(temp)\n",
    "                temp = ''\n",
    "            elif path[i] != \"/\":\n",
    "                temp = temp + path[i]\n",
    "        #将数组拼成string\n",
    "        if len(res) == 0:\n",
    "            return \"/\"\n",
    "        result = \"\"\n",
    "        print(res)\n",
    "        for item in res:\n",
    "            result = result + \"/\" + item \n",
    "        return result\n",
    "        \n",
    "    \n",
    "    \n",
    "                    \n",
    "                \n",
    "                \n",
    "                \n",
    "                "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def simplifyPath(self, path: str) -> str:\n",
    "        strack = []\n",
    "        path_list = path.split('/')\n",
    "        for i in path_list:\n",
    "            if i == '..' and len(strack)>0:\n",
    "                strack.pop()\n",
    "            elif i == '.' or i == '' or i == '..' and len(strack)==0:\n",
    "                pass\n",
    "            else:\n",
    "                strack.append(i)\n",
    "\n",
    "        return '/'+'/'.join(strack)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def simplifyPath(self, path: str) -> str:\n",
    "        stack = []\n",
    "        path = path.split('/')\n",
    "        for i in path:\n",
    "            if i == '..':\n",
    "                if stack:\n",
    "                    stack.pop()\n",
    "            elif i and i != '.':\n",
    "                stack.append(i)\n",
    "        return '/' + '/'.join(stack)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def simplifyPath(self, path: str) -> str:\n",
    "        stack = []\n",
    "        for i in path.split('/'):\n",
    "            if i not in ['', '.', '..']:\n",
    "                stack.append(i)\n",
    "            elif i == '..' and stack:\n",
    "                stack.pop()\n",
    "        return \"/\" + \"/\".join(stack)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def simplifyPath(self, path: str) -> str:\n",
    "        if not path:\n",
    "            return path\n",
    "        stack = []\n",
    "        arr = path.split(\"/\")\n",
    "        for i in arr:\n",
    "            if not i or i == \".\" or (not stack and i ==\"..\"):\n",
    "                continue\n",
    "            elif i == \"..\":\n",
    "                stack.pop()\n",
    "            else:\n",
    "                stack.append(i)\n",
    "        return \"/\" +\"/\".join(stack)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def simplifyPath(self, path: str) -> str:\n",
    "        N = len(path)\n",
    "        stack = []\n",
    "        i = 0\n",
    "        while i <N:\n",
    "            if path[i] == '/':\n",
    "                i += 1\n",
    "                continue\n",
    "            elif path[i] == '.' :\n",
    "                start = i \n",
    "                while i < N and path[i] != '/':\n",
    "                    i += 1\n",
    "                cnt = i - start\n",
    "                if cnt == 2 and stack:\n",
    "                    stack.pop()\n",
    "                elif cnt > 2:\n",
    "                    stack.append(path[start:i])\n",
    "            else:\n",
    "                start = i \n",
    "                while i <N and path[i] !='.' and path[i] != '/':\n",
    "                    i += 1\n",
    "                s = path[start:i]\n",
    "                stack.append(s)\n",
    "        return '/'+\"/\".join(stack)\n",
    "            "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def simplifyPath(self, path: str) -> str:\n",
    "        #自写\n",
    "        s=path.split('/')\n",
    "        #print(s)\n",
    "        st=[]\n",
    "        for i in range(len(s)):\n",
    "            if s[i]=='' or s[i]=='.':\n",
    "                continue\n",
    "            elif s[i]=='..':\n",
    "                if st:\n",
    "                    st.pop()\n",
    "            else:\n",
    "                st.append(s[i])\n",
    "       \n",
    "        if not st:\n",
    "            return '/'\n",
    "        x='/'.join(st)\n",
    "        return '/'+x\n",
    "        #return \"/\" + \"/\".join(stack)\n",
    "\n",
    "               \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def simplifyPath(self, path: str) -> str:\n",
    "        path = path.split(\"/\")\n",
    "\n",
    "        res = []\n",
    "        for p in path:\n",
    "            if p == \".\":\n",
    "                pass\n",
    "            elif p == \"..\":\n",
    "                if len(res)>0:\n",
    "                    res.pop()\n",
    "            elif p == \"\":\n",
    "                pass\n",
    "            else:\n",
    "                res.append(p)\n",
    "        return \"/\"+\"/\".join(res)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def simplifyPath(self, path: str) -> str:\n",
    "        a = path.split('/')\n",
    "        b = []\n",
    "        for aa in a:\n",
    "            if aa != '' and aa != '.':\n",
    "                if aa == '..':\n",
    "                    if b:\n",
    "                        b.pop()\n",
    "                else:\n",
    "                    b.append(aa)\n",
    "        c ='/'\n",
    "        for bb in b:\n",
    "            c = c + bb + \"/\"\n",
    "        if len(c) > 1:\n",
    "            return c[0:-1]\n",
    "        else:\n",
    "            return '/'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def simplifyPath(self, path: str) -> str:\n",
    "        stack = []\n",
    "        ops = path.split(\"/\")\n",
    "        for op in ops:\n",
    "            if op == \"\" or op == \".\":\n",
    "                continue\n",
    "            if op == \"..\":\n",
    "                if len(stack) == 0:\n",
    "                    continue\n",
    "                else:\n",
    "                    stack.pop()\n",
    "            else:\n",
    "                stack.append(op)\n",
    "        re = \"\"\n",
    "        for one in stack:\n",
    "            re += \"/\"\n",
    "            re += one\n",
    "        if re == \"\":\n",
    "            re = \"/\"\n",
    "        return re\n",
    "            "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def simplifyPath(self, path: str) -> str:\n",
    "        ls = []\n",
    "        tmp1 = path.split('/')\n",
    "        tmp2 = [i for i in tmp1 if len(i)>=1]\n",
    "        for i in tmp2:\n",
    "            if i == '..' and ls:\n",
    "                ls.pop()\n",
    "            elif i == '..' and not ls:\n",
    "                pass\n",
    "            elif i != '.':\n",
    "                ls.append(i)\n",
    "        res = ''\n",
    "        for i in ls:\n",
    "            res = res + '/' + i\n",
    "        return res if len(res) > 0 else '/'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def simplifyPath(self, path: str) -> str:\n",
    "        stack = []\n",
    "        for p in path.split('/'):\n",
    "            if p not in ['.', '..', '']:\n",
    "                stack.append(p)\n",
    "            elif p == '..' and stack:\n",
    "                stack.pop()\n",
    "        return f\"/{'/'.join(stack)}\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def simplifyPath(self, path: str) -> str:\n",
    "        a=[]\n",
    "        for i in path.split(\"/\"):\n",
    "            if i == '..' and a:\n",
    "                a.pop()\n",
    "            elif i not in '..':\n",
    "                a.append(i)\n",
    "        return '/'+'/'.join(a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def simplifyPath(self, path: str) -> str:\n",
    "        p = []\n",
    "        for x in path.split('/'):\n",
    "            if x == '.' or x == '': continue\n",
    "            elif x == '..':\n",
    "                if len(p) > 0:\n",
    "                    p.pop()\n",
    "            else:\n",
    "                p.append(x)\n",
    "        if p:  return \"/\" + '/'.join(p)\n",
    "        return '/'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def simplifyPath(self, path: str) -> str:\n",
    "        names = path.split(\"/\")\n",
    "        stack = list()\n",
    "        for name in names:\n",
    "            if name == \"..\":\n",
    "                if stack:\n",
    "                    stack.pop()\n",
    "            elif name and name != \".\":\n",
    "                stack.append(name)\n",
    "        return \"/\" + \"/\".join(stack)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def simplifyPath(self, path: str) -> str:\n",
    "        stack = []\n",
    "        path = path.split('/')\n",
    "        print(path)\n",
    "        for element in path:\n",
    "            if element == '' or element == '.':\n",
    "                continue\n",
    "            elif element == \"..\":\n",
    "                if stack:\n",
    "                    stack.pop()\n",
    "            else:\n",
    "                stack.append(element)\n",
    "        print(stack)\n",
    "        res = \"\"\n",
    "        if len(stack) == 0:\n",
    "            return \"/\"\n",
    "        for x in stack:\n",
    "            res += '/' + x \n",
    "        return res\n",
    "            \n",
    "\n",
    "        # path_list = path.split('/') \n",
    "        # stack = []\n",
    "        # for word in path_list:\n",
    "        #     if word == '..':\n",
    "        #         if stack: \n",
    "        #             stack.pop()\n",
    "        #     elif word == '.' or word == '': \n",
    "        #         continue\n",
    "        #     else: \n",
    "        #         stack.append(word)\n",
    "        # res = \"\"\n",
    "        # if len(stack) == 0:\n",
    "        #     return '/'\n",
    "        # for word in stack:\n",
    "        #     res += '/' + word \n",
    "            \n",
    "        # return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def simplifyPath(self, path: str) -> str:\n",
    "        stack = []\n",
    "        path = path.split('/')\n",
    "        for s in path:\n",
    "            if s == \".\":\n",
    "                pass\n",
    "            elif s == \"\":\n",
    "                pass\n",
    "            elif s == \"..\":\n",
    "                if not stack:\n",
    "                    stack.append(\"/\")\n",
    "                stack.pop()\n",
    "            else:\n",
    "                stack.append(s)\n",
    "            print(stack)\n",
    "        return \"/\" + \"/\".join(stack)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def simplifyPath(self, path: str) -> str:\n",
    "        return os.path.realpath(path)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def simplifyPath(self, path: str) -> str:\n",
    "        stack=[]\n",
    "        start=0#路径起点\n",
    "        while start<len(path):\n",
    "            while start<len(path) and path[start]=='/':\n",
    "            #起始路径开始/开始，找到第一个不为/的内容\n",
    "                start+=1\n",
    "            if start>=len(path):break#越界\n",
    "            end=start#开始遍历寻找第一条路径，终止也从起点开始遍历\n",
    "            while end<len(path) and path[end]!='/':\n",
    "                end+=1#找到终点位置\n",
    "            name=path[start:end]#一条路径的内容\n",
    "            if name ==\"..\" and stack:#如果目录名是返回上一级，从队尾弹出一个目录名\n",
    "                stack.pop()\n",
    "            elif name!=\".\" and name!=\"..\":\n",
    "                stack.append(name)#目录名不为..和.则加入队尾形成一条路径\n",
    "            start=end#此时的终点处为新的路径的起点\n",
    "        return \"/\"+\"/\".join(stack)#单斜杠分开每条路径，并且每条路径开头有/\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def simplifyPath(self, path: str) -> str:\n",
    "        stack=[]\n",
    "        #遇到空字符和‘.’跳过，遇到‘..’将上一次加入的路径名弹出出栈，其他的情况加入路径名，最后用“/”连接\n",
    "        for num in path.split(\"/\"):#将/隔开的字符拆开形成单独的字符串数组\n",
    "            if num==\"..\" and stack:\n",
    "                stack.pop()\n",
    "            if num not in \"..\":\n",
    "                stack.append(num)\n",
    "        return \"/\"+\"/\".join(stack)\n",
    "\n",
    "          "
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 2
}
